﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Encodings.Web;
using Kugar.Core.BaseStruct;
using Kugar.Core.ExtMethod;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using Webdiyer.AspNetCore;

namespace Kugar.UI.Web.AdminLTE.PageControls.PageCommon
{
    public class PageCommon_Pager : ControlBase
    {
        internal int _currentIndex = 1;
        private int _totalCount = 0;
        internal int _pageSize = 0;
        //private Webdiyer.WebControls.Mvc.HtmlPager _pager=null;
        private static PagerOptions _options = null;
        private PagerOptions _currentOptions = null;
        private bool _isAjax = false;
        private string _actionUrl = "";
        private string _updateElementID = "";
        private string _forID = "";
        private string _placeholder = "页码";

        static PageCommon_Pager()
        {
            _options = new PagerOptions
            {
                PageIndexParameterName = "pageindex",
                TagName = "ul",
                CssClass = "pagination pull-right",
                CurrentPagerItemTemplate = "<li class=\"active\"><a href=\"#\">{0}</a></li>",
                DisabledPagerItemTemplate = "<li class=\"disabled\"><a>{0}</a></li>",
                PagerItemTemplate = "<li>{0}</li>",
                HorizontalAlign = "right",
                ShowFirstLast = false,
                PrevPageText = "<",
                NextPageText = ">",
                FirstPageText = "|<",
                LastPageText = ">|",
                NumericPagerItemCount = 5,
                AutoHide = true,
                //NavigationPagerItemTemplate = "<li ><input type=\"number\" placeholder=\"页码\" class=\"form-control pagerinput\"/></li>"
                //Id = "bootstrappager"
            };


        }

        public PageCommon_Pager PageIndexParameterName(string name)
        {
            _currentOptions.PageIndexParameterName = name;

            return this;
        }

        public PageCommon_Pager(ViewContext viewContext) : base(viewContext)
        {
            _currentOptions = clone();
        }

        public PageCommon_Pager Source<T>(VM_PagedList<T> lst)
        {
            _currentIndex = lst.PageIndex;
            _totalCount = lst.TotalCount;
            _pageSize = lst.PageSize;

            return this;
        }

        public PageCommon_Pager RecordCount(int totalRecordCount)
        {
            _totalCount = totalRecordCount;

            return this;
        }

        public PageCommon_Pager PageSize(int pageSize)
        {
            _pageSize = pageSize;

            return this;
        }

        public PageCommon_Pager BoxPlaceholder(string placeholder)
        {
            _placeholder = placeholder;

            return this;
        }

        public PageCommon_Pager CurrentIndex(int pageIndex)
        {
            _currentIndex = pageIndex;

            return this;
        }

        public PageCommon_Pager ShowFirstLast(bool isShow = true)
        {
            _currentOptions.ShowFirstLast = isShow;

            return this;
        }

        public PageCommon_Pager ShowPagerBox(bool isShow)
        {
            _currentOptions.ShowNumericPagerItems = isShow;

            return this;
        }


        /// <summary>
        /// 使用异步分页功能
        /// </summary>
        /// <param name="elementID">ajax获取数据后,替换那个元素,必须是id</param>
        /// <param name="actionUrl">获取数据的链接,将会自动根据pagekey替换分页页码,如果该值为空,则使用pager控件生成的url进行获取整页数据,并只替换部分html</param>
        /// <returns></returns>
        public PageCommon_Pager UpdateElementID(string elementID, string actionUrl = "")
        {
            if (!string.IsNullOrWhiteSpace(_updateElementID))
            {
                _updateElementID = elementID;
                _actionUrl = actionUrl.ToStringEx();
                _isAjax = true;

            }
           

            return this;
        }

        public PageCommon_Pager ForControlID(string id)
        {
            _forID = id;

            return this;
        }

        public override HtmlString Render()
        {
            //var str = Html.Pager(_totalCount, _pageSize, _currentIndex, _options).ToHtmlString();
            //ViewContext.Writer.WriteLine("sss");

            _currentOptions.HtmlAttributes = _currentOptions.HtmlAttributes ?? new Dictionary<string, object>();

            if (_isAjax && !string.IsNullOrWhiteSpace(_updateElementID))
            {
                _currentOptions.HtmlAttributes.Add("data-isajax", "true");
                _currentOptions.HtmlAttributes.Add("data-updateelementid", _updateElementID);
                _currentOptions.HtmlAttributes.Add("data-actionurl", _actionUrl);
                _currentOptions.CssClass += " ajaxpager";
            }

            _currentOptions.HtmlAttributes.AddOrUpdate("data-forid",_forID);

            //if (_placeholder!="页码")
            //{
            //    _currentOptions.NavigationPagerItemTemplate =
            //        _currentOptions.NavigationPagerItemTemplate.Replace("页码", _placeholder);
            //}

            var pageIndexBox = $"<div class=\"pull-right pageIndexBox\"><input type=\"number\" placeholder=\"{_placeholder}\" class=\"form-control pagerinput\"/></div>";
            if (_totalCount <= 0 || _pageSize <= 0 || _totalCount <= _pageSize || Math.Ceiling(_totalCount * 1.0 / _pageSize) < _currentIndex)
            {
                pageIndexBox = "";
            }

            var pager = new HtmlPager(Html, _totalCount, _pageSize, _currentIndex, _currentOptions);
            
            using (var writer=new StringWriter())
            {
                pager.WriteTo(writer,HtmlEncoder.Default);

                return new HtmlString(pageIndexBox + writer.ToStringEx());
            }

            //var str = _pager.ToHtmlString();
            // ViewContext.Writer.Write(str);
            //ViewContext.Writer.WriteLine(_pager.ToHtmlString());
            // return MvcHtmlString.Empty;
            
        }



        private PagerOptions clone()
        {
            /*
             *new PagerOptions
            {
                PageIndexParameterName = "pageindex",
                ContainerTagName = "ul",
                CssClass = "pagination pull-right",
                CurrentPagerItemTemplate = "<li class=\"active\"><a href=\"#\">{0}</a></li>",
                DisabledPagerItemTemplate = "<li class=\"disabled\"><a>{0}</a></li>",
                PagerItemTemplate = "<li>{0}</li>",
                HorizontalAlign = "right",
                ShowFirstLast = false,
                PrevPageText = "<",
                NextPageText = ">",
                NumericPagerItemCount = 5
                
                //Id = "bootstrappager"
            };
             *
             */

            return new PagerOptions()
            {
                PageIndexParameterName = _options.PageIndexParameterName,
                TagName = _options.TagName,
                CssClass = _options.CssClass,
                CurrentPagerItemTemplate = _options.CurrentPagerItemTemplate,
                DisabledPagerItemTemplate = _options.DisabledPagerItemTemplate,
                PagerItemTemplate = _options.PagerItemTemplate,
                HorizontalAlign = _options.HorizontalAlign,
                ShowFirstLast = _options.ShowFirstLast,
                PrevPageText = _options.PrevPageText,
                NextPageText = _options.NextPageText,
                FirstPageText = _options.FirstPageText,
                LastPageText = _options.LastPageText,
                NumericPagerItemCount = _options.NumericPagerItemCount,
                AutoHide = _options.AutoHide,
                NavigationPagerItemTemplate= _options.NavigationPagerItemTemplate
            };
        }
    }
}
